package io.gitee.zicai.task.job

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler
import org.springframework.scheduling.support.CronTrigger
import org.springframework.stereotype.Component
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * JobService
 * @author zicai
 * @since 2020-05-18
 */
@Component
open class JobService {

    @Autowired
    private lateinit var threadPoolTaskScheduler: ThreadPoolTaskScheduler

    fun start(jobName: String) {
        if (JobHolder.isStart(jobName)) {
            println("${now()} - $jobName is running...")
            return
        }
        val job = JobHolder.makeJob {
            println("${now()} - $jobName start")
            Random().nextInt(8).plus(2)
                    .also { println("${now()} - ${Thread.currentThread().name} - $jobName - sleep $it seconds...") }
                    .also {
                        repeat(it) {
                            println("${now()} - ${Thread.currentThread().name} - $jobName - sleep.")
                            TimeUnit.SECONDS.sleep(1)
                        }
                    }
            println("${now()} - $jobName end")
        }
        JobHolder.add(jobName, threadPoolTaskScheduler.schedule(job, CronTrigger("0/10 * * * * ? ")))
        println("${now()} - $jobName saved.")
    }

    fun remove(jobName: String) {
        println("${now()} - remove job : $jobName")
        JobHolder.remove(jobName)
    }

    private fun now() = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
}